﻿using DevExpress.XtraEditors;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using static BW.Mes.WinForms.BasicData.WorkshopForm;
using static BW.Mes.WinForms.BasicData.LineForm1;

namespace BW.Mes.WinForms.BasicData
{
    public partial class AddLineForm : XtraForm
    {
        private readonly HttpClient _httpClient;
        private readonly string _apiBaseUrl = "http://120.26.197.100:8022";
        private LineModel _editLine;

        public AddLineForm(LineModel line = null)
        {
            InitializeComponent();
            var handler = new HttpClientHandler
            {
                ServerCertificateCustomValidationCallback = (req, cert, chain, errors) => true
            };
            _httpClient = new HttpClient(handler);
            _editLine = line;
            this.Load += AddLineForm_Load;
            this.Load += AddLineForm_AutoGenLineCode;
        }

        private async void AddLineForm_Load(object sender, EventArgs e)
        {
            await LoadWorkshops();
            if (_editLine != null)
            {
                textEditLineCode.Text = _editLine.LineCode;
                textEditLineName.Text = _editLine.LineName;
                textEditLineMsg.Text = _editLine.LineMsg;
                textEditLineCode.Properties.ReadOnly = true;
            }
        }

        private async void AddLineForm_AutoGenLineCode(object sender, EventArgs e)
        {
            if (_editLine != null) return;
            string today = DateTime.Now.ToString("yyyyMMdd");
            string prefix = $"CX{today}";
            int maxSerial = 0;
            try
            {
                var response = await _httpClient.GetAsync($"{_apiBaseUrl}/T2/Line/GetLine");
                if (response.IsSuccessStatusCode)
                {
                    var json = await response.Content.ReadAsStringAsync();
                    var jsonObject = Newtonsoft.Json.Linq.JObject.Parse(json);
                    var listToken = jsonObject["pageDatas"] ?? jsonObject["data"] ?? jsonObject["result"];
                    if (listToken != null)
                    {
                        var lines = JsonConvert.DeserializeObject<List<LineModel>>(listToken.ToString());
                        if (lines != null)
                        {
                            foreach (var item in lines)
                            {
                                string code = item.LineCode;
                                if (!string.IsNullOrEmpty(code) && code.StartsWith(prefix))
                                {
                                    string serialStr = code.Substring(prefix.Length);
                                    if (int.TryParse(serialStr, out int serial))
                                    {
                                        if (serial > maxSerial) maxSerial = serial;
                                    }
                                }
                            }
                        }
                    }
                }
            }
            catch { }
            string newCode = $"{prefix}{(maxSerial + 1).ToString("D3")}";
            textEditLineCode.Text = newCode;
            textEditLineCode.Properties.ReadOnly = true;
        }

        private async Task LoadWorkshops()
        {
            try
            {
                HttpResponseMessage response = await _httpClient.GetAsync($"{_apiBaseUrl}/T2/Workshop/GetWorkshop");
                response.EnsureSuccessStatusCode();
                string responseBody = await response.Content.ReadAsStringAsync();
                var jsonObject = Newtonsoft.Json.Linq.JObject.Parse(responseBody);
                if (jsonObject["pageDatas"] != null)
                {
                    string dataJson = jsonObject["pageDatas"].ToString();
                    var workshops = JsonConvert.DeserializeObject<List<WorkShopModel>>(dataJson);

                    lookUpEditWorkshop.Properties.DataSource = workshops;
                    lookUpEditWorkshop.Properties.DisplayMember = "WorkshopName";
                    lookUpEditWorkshop.Properties.ValueMember = "Id";

                    lookUpEditWorkshop.Properties.Columns.Clear();
                    lookUpEditWorkshop.Properties.Columns.Add(new DevExpress.XtraEditors.Controls.LookUpColumnInfo("WorkshopName", "车间名称"));
                    lookUpEditWorkshop.Properties.NullText = "请选择所属车间";
                }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show($"加载车间数据失败: {ex.Message}", "错误");
            }
        }

        private async void btnOK_Click(object sender, EventArgs e)
        {
            if (lookUpEditWorkshop.EditValue == null)
            {
                XtraMessageBox.Show("请选择一个所属车间。");
                return;
            }

            var model = new
            {
                Id = _editLine?.Id ?? 0,
                LineCode = textEditLineCode.Text,
                LineName = textEditLineName.Text,
                LineMsg = textEditLineMsg.Text,
                WorkshopId = (long)lookUpEditWorkshop.EditValue,
                CreatedBy = "wyj"
            };

            try
            {
                var json = JsonConvert.SerializeObject(model);
                var content = new StringContent(json, Encoding.UTF8, "application/json");
                HttpResponseMessage response;
                if (_editLine == null)
                {
                    response = await _httpClient.PostAsync($"{_apiBaseUrl}/T2/Line/AddLine", content);
                }
                else
                {
                    response = await _httpClient.PutAsync($"{_apiBaseUrl}/T2/Line/UpdateLine", content);
                }

                if (response.IsSuccessStatusCode)
                {
                    XtraMessageBox.Show(_editLine == null ? "添加成功！" : "修改成功！");
                    this.DialogResult = DialogResult.OK;
                    this.Close();
                }
                else
                {
                    string errorContent = await response.Content.ReadAsStringAsync();
                    XtraMessageBox.Show($"{(_editLine == null ? "添加" : "修改")}失败：{response.ReasonPhrase} - {errorContent}");
                }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show($"提交数据时出错: {ex.Message}", "错误");
            }
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void AddLineForm_Load_1(object sender, EventArgs e)
        {

        }

        private void lookUpEditWorkshop_EditValueChanged(object sender, EventArgs e)
        {

        }
    }
}